package com.zork.cmdb.webapi.common.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author chenjh
 * @date 2018/5/10
 * @description
 */
@Aspect
@Component
public class Logger {

    private org.slf4j.Logger logger = null;

    @Pointcut("execution(public * com.zork.cmdb.webapi.api.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Map<String, String[]> queryParam = request.getParameterMap();
        logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
        logger.info("url={}; method={}; ip={}", request.getRequestURI(), request.getMethod(), request.getRemoteAddr());
        logger.info("pathParam={}", joinPoint.getArgs());
        logger.info("queryParam={}", JSON.toJSONString(queryParam));
    }

//    @After("log()")
//    public void doAfter() {
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        logger.info("url = {} end of execution", request.getRequestURL());
//    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturn(Object object) {
        logger.info("response={}", object.toString());
    }
}